<script setup>
import {ref, onMounted, computed} from 'vue'
import { sessionApi, pageUserApi, saveUserApi, procUsersApi, oneUserApi, selRoleApi, treeTypeApi } from '@/common/api'
import router from '@/common/router'
import Note from '@/components/notify'
import Msg from '@/components/message'
import Confirm from '@/components/confirm'
import { CScrollbar } from 'c-scrollbar'
import Pager from '@/components/pagination/UbtPager.vue'
import UbtTreeSel from '@/components/cascader/UbtTreeSel.vue'
import UbtSelect from '@/components/select/UbtSelect.vue'

// 自动加载，判断权限
onMounted(() => {
  checkAuth()
})

const procAuth = ref({
  addAuth: false,
  delAuth: false,
  edtAuth: false,
  pasAuth: false,
  unpAuth: false
})
// checkAuth 获取权限
const checkAuth = async () => {
  const res = await sessionApi()
  if (res.code === 200) {
    const userBtnCode = res.data.btnCodes
    procAuth.value = {
      addAuth: userBtnCode.indexOf('1001010501') !== -1,
      delAuth: userBtnCode.indexOf('1001010502') !== -1,
      edtAuth: userBtnCode.indexOf('1001010503') !== -1,
      pasAuth: userBtnCode.indexOf('1001010504') !== -1,
      unpAuth: userBtnCode.indexOf('1001010505') !== -1
    }
    list(0, 1)
    selRole('')
    selOrg()
  } else {
    Msg({ kind: 'error', txt: res.msg })
    router.replace('/login')
  }
}

const schObj = {
  schName: '',
  roleId: '',
  roleName: '',
  roleCode: '',
  deptId: '',
  deptName: '',
  deptCode: '',
  states: 0,
  stateName: '',
  stateCode: '',
  offset: 0,
  limit: 20
}
const schRef = ref(schObj)
const total = ref(0)
const curPage = ref(1)
const userList = ref([])
const hasData = ref(false)
const checkList = ref([])
// list 列表展示
const list = async (offset, cur) => {
  schRef.value.offset = offset || 0
  curPage.value = cur || 1
  hasData.value = false
  const res = await pageUserApi(schRef.value)
  if(res.code === 200 && res.data) {
    hasData.value = true
    total.value = res.data.total
    userList.value = res.data.list
    idList.value = []
    checkList.value = []
    allCheck.value = false
    res.data.list.forEach(() => {
      checkList.value.push(false)
    })
  }
}

// search 筛选
const schShow = ref(false)
const search = () => {
  schShow.value = !schShow.value
}

// clrSch 重置搜索框
const clrSch = () => {
  schRef.value = {
    schName: '',
    roleId: '',
    roleName: '',
    roleCode: '',
    deptId: '',
    deptName: '',
    deptCode: '',
    states: 0,
    stateName: '',
    stateCode: '',
    offset: 0,
    limit: 20
  }
  list(0, 1)
}

// 选择效果实现
const idList = ref([])
const allCheck = ref(false)
// checkAll 全选
const checkAll = () => {
  idList.value = []
  checkList.value = []
  allCheck.value = !allCheck.value
  if(allCheck.value) {
    userList.value.forEach(item => {
      idList.value.push(item.userId)
      checkList.value.push(true)
    })
  } else {
    userList.value.forEach(() => {
      checkList.value.push(false)
    })
  }
}
// checkCurId 单选
const checkCurId = (idx, userId) => {
  if(!checkList.value[idx]) {
    idList.value.push(userId)
  } else {
    const index = idList.value.findIndex(id => {
      if (id === userId) {
        return true
      }
    })
    idList.value.splice(index, 1)
  }
  checkList.value[idx] = !checkList.value[idx]
}

const userObj = {
  userId: '',
  usname: '',
  passwd: '',
  nickName: '',
  mobile: '',
  roleId: '',
  roleName: '',
  roleCode: '',
  deptId: '',
  deptName: '',
  deptCode: '',
  kind: 2
}
const userForm = ref(userObj)
// add 新增
const showModal = ref(false)
const add = () => {
  showModal.value = true
}
// update 修改
const update = async (userId) => {
  const res = await oneUserApi({userId})
  if(res.code === 200) {
    showModal.value = true
    userForm.value = res.data
    userForm.value.deptId = res.data.deptId
    userForm.value.deptName = res.data.typeName
    userForm.value.deptCode = res.data.typeCode
  } else {
    Msg({ kind: 'info', txt: '暂无内容' })
  }
}
// save 保存提交
const save = async () => {
  let userId = userForm.value.userId
  let usname = userForm.value.usname
  let passwd = userForm.value.passwd
  let nickName = userForm.value.nickName
  let mobile = userForm.value.mobile
  let deptId = userForm.value.deptId
  let roleId = userForm.value.roleId
  if(usname === '' || usname.length > 50) {
    Msg({ kind: 'warn', txt: '用户的昵称不能为空，且长度不超过50个字符！' })
    return
  } else if((userId==='' && (passwd==='' || passwd.length<6 || passwd.length>30)) || (userId!=='' && passwd!=='' && (passwd.length<6 || passwd.length>30))) {
    Msg({ kind: 'warn', txt: '用户的登录密码不能为空，且长度为6至30位！' })
    return
  } else if(nickName === '' || nickName.length > 50) {
    Msg({ kind: 'warn', txt: '用户昵称不能为空，且长度不超过50个字符！' })
    return
  } else if(mobile === '' || mobile.length !== 11) {
    Msg({ kind: 'warn', txt: '手机号码不能为空，且长度为11个字符！' })
    return
  } else if(deptId === '' || deptId.length !== 21) {
    Msg({ kind: 'warn', txt: '用户所属组织不能为空！' })
    return
  } else if(roleId === '' || roleId.length !== 21) {
    Msg({ kind: 'warn', txt: '用户角色不能为空！' })
    return
  }
  const res = await saveUserApi(userForm.value)
  if(res.code === 200) {
    closeModal()
    list(0, 1)
    Note({ kind: 'success', title: '成功', txt: '恭喜您，用户信息保存成功！' })
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// closeModal 关闭弹出层，并重置表单数据
const closeModal = () => {
  showModal.value = false
  userForm.value = {
    userId: '',
    usname: '',
    passwd: '',
    nickName: '',
    mobile: '',
    roleId: '',
    roleName: '',
    roleCode: '',
    deptId: '',
    deptName: '',
    deptCode: '',
    kind: 2
  }
}

// chkShowed 单选框效果
const chkKind = (idx) => {
  switch(idx) {
    case 1:
      userForm.value.kind = 1
      break
    case 2:
      userForm.value.kind = 2
      break
    default:
      userForm.value.kind = 1
      break
  }
}

// process 删除用户
const process = (states) => {
  if(!idList || idList.value.length===0) {
    Msg({ kind: 'warn', txt: '请至少选择一项再操作！' })
    return
  }
  Confirm('确定要删除选中的用户吗？').then(() => {
    procUsers(states)
  }).catch(() => {
    Msg({ kind: 'info', txt: "取消处理选中的数据！" })
  })
}
// procUsers 删除用户实现，分离出来防止调用时异步报错
const procUsers = async (states) => {
  let userIds = idList.value.join(',')
  const res = await procUsersApi({ userIds, states })
  if(res.code === 200) {
    list(0, 1)
    Note({ kind: 'success', title: '成功', txt: '恭喜您，用户操作成功！' })
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

const roleList = ref([])
const selRole = async (schName) => {
  const res = await selRoleApi({schName: schName})
  if(res.code === 200) {
    roleList.value = res.data
  }
}

const selByKey = (schName) => {
  selRole(schName)
}

// selOrg 获取分类下拉列表
const deptList = ref([])
const selOrg = async () => {
  const res = await treeTypeApi({kind: 1})
  if(res.code === 200) {
    deptList.value = res.data
  }
}

const stateList = ref([{selId: 1, selName: '正常', selCode: '101', chked: false}, {selId: 4, selName: '冻结', selCode: '104', chked: false}])

const setValue = (item, kind) => {
  switch(kind) {
    case 1:
      schRef.value.roleId = item.selId
      schRef.value.roleName = item.selName
      schRef.value.roleCode = item.selCode
      break
    case 2:
      userForm.value.roleId = item.selId
      userForm.value.roleName = item.selName
      userForm.value.roleCode = item.selCode
      break
    case 3:
      schRef.value.deptId = item.selId
      schRef.value.deptName = item.selName
      schRef.value.deptCode = item.selCode
      break
    case 4:
      userForm.value.deptId = item.selId
      userForm.value.deptName = item.selName
      userForm.value.deptCode = item.selCode
      break
    case 5:
      schRef.value.states = item.selId
      schRef.value.stateName = item.selName
      schRef.value.stateCode = item.selCode
      break
  }
}

// fmtState 状态转码
const fmtState = computed(() => {
  return (states) => {
    let str
    switch (states) {
      case 1:
        str = '正常'
        break;
      case 3:
        str = '冻结'
        break;
      default:
        str = '其它'
        break
    }
    return str
  }
})

// fmtKind 种类转码
const fmtKind = computed(() => {
  return (kind) => {
    let str
    switch (kind) {
      case 1:
        str = '领导'
        break;
      case 2:
        str = '员工'
        break;
      default:
        str = '其它'
        break
    }
    return str
  }
})
</script>

<template>
  <div class="a">
    <!-- 头部用户 -->
    <div class="b">
      <div v-if="procAuth.addAuth" class="btn-p" title="新增" @click="add()"><i class="iconfont doc_text"></i> 新增</div>
      <div v-if="procAuth.delAuth" class="btn-d" title="删除" @click="process(2)"><i class="iconfont trash"></i> 删除</div>
      <div v-if="procAuth.pasAuth" class="btn-d" title="上线" @click="process(1)"><i class="iconfont text_badge_checkmark"></i> 上线</div>
      <div v-if="procAuth.unpAuth" class="btn-d" title="下线" @click="process(3)"><i class="iconfont text_badge_xmark"></i> 下线</div>
      <div class="btn-r" title="筛选" @click="search()"><i class="iconfont search"></i></div>
      <div class="btn-r" title="刷新" @click="list(0, 1)"><i class="iconfont arrow__circlepath"></i></div>
    </div>
    <!-- 中部数据 -->
    <div class="c" v-if="schShow">
      <div class="d"><input type="text" v-model="schRef.schName" placeholder="请输入关键字" class="e" /></div>
      <div class="d"><ubt-tree-sel :kind="3" :tree-list="deptList" :inboxed="true" :curName="schRef.deptName!=='' ? schRef.deptName+'['+schRef.deptCode+']' : ''" pre-name="组织" @setValue="setValue" /></div>
      <div class="d"><ubt-select :kind="1" :sel-list="roleList" :inboxed="true" :cur-name="schRef.roleName ? schRef.roleName + '[' + schRef.roleCode + ']' : ''" pre-name="岗位" @setValue="setValue" @selByKey="selByKey" /></div>
      <div class="d"><ubt-select :kind="5" :sel-list="stateList" :inboxed="true" :cur-name="schRef.stateName ? schRef.stateName + '[' + schRef.stateCode + ']' : ''" pre-name="状态" @setValue="setValue" /></div>
      <div class="f">
        <div class="btn-p" @click="list(0, 1)"><i class="iconfont search"></i> 筛选</div>
        <div class="btn-d" @click="clrSch()"><i class="iconfont arrowshape_turn_up_left"></i> 重置</div>
      </div>
    </div>
    <div class="g" v-if="hasData">
      <table>
        <tr>
          <th style="width: 5%;"><i @click="checkAll()" :class="['iconfont', allCheck ? 'checkmark_square_fill chked' : 'app chk']"></i></th>
          <th style="width: 12%;">昵称</th>
          <th style="width: 13%;">账号</th>
          <th style="width: 13%;">手机号</th>
          <th style="width: 13%;">组织</th>
          <th style="width: 12%;">岗位</th>
          <th style="width: 8%;">种类</th>
          <th style="width: 7%;">状态</th>
          <th style="width: 8%;">操作</th>
        </tr>
        <tr v-for="(curUser, index) in userList" :key="curUser.userId" class="tr-style">
          <td class="txt-center"><i @click="checkCurId(index, curUser.userId)" :class="['iconfont', checkList[index] ? 'checkmark_square_fill chked' : 'app chk']"></i></td>
          <td class="txt-center">{{curUser.nickName}}</td>
          <td class="txt-center">{{curUser.usname}}</td>
          <td class="txt-center">{{curUser.mobile}}</td>
          <td class="txt-center">{{curUser.deptName}}</td>
          <td class="txt-center">{{curUser.roleName}}</td>
          <td class="txt-center">{{fmtKind(curUser.kind)}}</td>
          <td class="txt-center">{{fmtState(curUser.states)}}</td>
          <td class="txt-center">
            <span v-if="procAuth.edtAuth" class="cl-blue" title="修改" @click="update(curUser.userId)"><i class="iconfont square_pencil"></i> 修 改</span>
          </td>
        </tr>
      </table>
      <Pager v-if="hasData" :limit="schRef.limit" :total="total" :page="curPage" @turn="list" />
    </div>
    <div v-else class="no-data">暂无内容</div>

    <!-- 新增、修改弹出层 -->
    <transition name="fade-mod" appear>
      <div v-if="showModal" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 800px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont doc_text fs20"></i> 保存用户信息</div>
              <div class="header-right" @click="closeModal()"><i class="iconfont xmark fs20"></i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="ipt-title"><span class="required">*</span>用户昵称</div>
                <div><input type="text" v-model="userForm.nickName" maxlength="50" placeholder="请输入用户名称" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>登录账号</div>
                <div><input type="text" v-model="userForm.usname" maxlength="50" placeholder="请输入登录账号" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>登录密码</div>
                <div><input type="text" v-model="userForm.passwd" maxlength="30" placeholder="请输入登录密码，修改时为空则不改密码" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>手机号码</div>
                <div><input type="text" v-model="userForm.mobile" maxlength="11" placeholder="手机号码" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>所属组织</div>
                <ubt-tree-sel :tree-list="deptList" :kind="4" :inboxed="false" :curName="userForm.deptName ? userForm.deptName+'['+userForm.deptCode+']' : ''" pre-name="所属组织" @setValue="setValue" />
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>用户岗位</div>
                <ubt-select :kind="2" :sel-list="roleList" :inboxed="false" :cur-name="userForm.roleName!=='' ? userForm.roleName+'['+userForm.roleCode+']' : ''" pre-name="岗位" @setValue="setValue" @selByKey="selByKey" />
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>用户种类</div>
                <div class="h">
                  <div class="cur i" @click="chkKind(1)"><i :class="['iconfont', userForm.kind===1 ? 'largecircle_fill_circle chked' : 'circle chk']"></i> 领导</div>
                  <div class="cur i" @click="chkKind(2)"><i :class="['iconfont', userForm.kind===1 ? 'circle chk' : 'largecircle_fill_circle chked']"></i> 员工</div>
                </div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-p" @click="save()"><i class="iconfont today_fill"></i> 保存</div>
              <div class="btn-d" @click="closeModal()"><i class="iconfont arrowshape_turn_up_left"></i> 取消</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
  </div>
</template>

<style scoped>
.a {width: 100%; height: 100%;}
.b {padding: 10px 20px; display: flex; display: -webkit-flex;}
.c {margin: 0 10px 10px 10px; border: 1px solid #CCC; display: flex; display: -webkit-flex; padding: 0 15px 15px 15px; flex-wrap: wrap; justify-content: flex-end;  }
.d {flex-grow: 1; margin-top: 15px;}
.e {width: 230px; padding: 8px;}
.f {display: flex; display: -webkit-flex; padding-top: 15px;}
.g {background-color: #FFF;}
.h {display: flex; display: -webkit-flex;}
.i {width: 80px; margin: 10px;}
</style>
